// composables/useLayout.ts

import { ref, computed, reactive } from 'vue'
import { tabBar } from '@/pages.json'

interface SystemInfo {
  safeAreaInsets?: {
    top: number
    bottom: number
  }
  navigationBarHeight?: number
  statusBarHeight?: number
  screenHeight: number
}

interface LayoutConfig {
  hasNavigationBar: boolean
  hasTabBar: boolean
  isFullScreen: boolean
}

const defaultConfig: LayoutConfig = {
  hasNavigationBar: true,
  hasTabBar: true,
  isFullScreen: false,
}

const globalConfig = ref<LayoutConfig>({ ...defaultConfig })
const systemInfo = ref<SystemInfo>(uni.getSystemInfoSync())

export function useLayout(initialConfig: Partial<LayoutConfig> = {}) {
  const localConfig = reactive<LayoutConfig>({ ...defaultConfig, ...initialConfig })

  const updateConfig = (newConfig: Partial<LayoutConfig>) => {
    Object.assign(localConfig, newConfig)
  }

  const resetConfig = () => {
    Object.assign(localConfig, defaultConfig)
  }

  const contentHeight = computed(() => {
    let height = systemInfo.value.screenHeight

    if (!localConfig.isFullScreen) {
      if (systemInfo.value.statusBarHeight) {
        height -= systemInfo.value.statusBarHeight
      }

      if (localConfig.hasNavigationBar && systemInfo.value.navigationBarHeight) {
        height -= systemInfo.value.navigationBarHeight
      }

      if (systemInfo.value.safeAreaInsets) {
        height -= systemInfo.value.safeAreaInsets.top
        height -= systemInfo.value.safeAreaInsets.bottom
      }

      if (localConfig.hasTabBar) {
        const tabBarHeight = Number(tabBar.height?.replace('px', '') || 0)
        height -= tabBarHeight
      }
    }

    return height
  })

  const bottomSafeAreaHeight = computed(() => {
    return systemInfo.value.safeAreaInsets?.bottom || 0
  })

  const tabBarHeight = computed(() => {
    return localConfig.hasTabBar ? Number(tabBar.height?.replace('px', '') || 0) : 0
  })

  const bottomTotalHeight = computed(() => {
    return bottomSafeAreaHeight.value + tabBarHeight.value
  })

  return {
    config: computed(() => localConfig),
    updateConfig,
    resetConfig,
    contentHeight,
    bottomSafeAreaHeight,
    tabBarHeight,
    bottomTotalHeight,
  }
}

// 全局配置方法
export function updateGlobalConfig(newConfig: Partial<LayoutConfig>) {
  Object.assign(globalConfig.value, newConfig)
}

export function resetGlobalConfig() {
  globalConfig.value = { ...defaultConfig }
}

export function getGlobalConfig() {
  return computed(() => globalConfig.value)
}
